from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from appium.webdriver.common.appiumby import AppiumBy
from selenium.common.exceptions import NoSuchElementException
import allure

#定位获取元素公共函数
def findElementBy(driver,By,view,attribute,AttributeValue):
    try :
        wait = WebDriverWait(driver, 10)
        if driver.capabilities.get('platformName')=='Android':
            if  By=='XPATH':
                element = wait.until(EC.visibility_of_all_elements_located((AppiumBy.XPATH,"//android.widget."+view+"[@"+attribute+"='"+AttributeValue+"']" ))) #可用
            elif By=='ID':
                element = wait.until(EC.visibility_of_all_elements_located((AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("'+AttributeValue+'")')))#可用
        elif driver.capabilities.get('platformName')=='ios':
            if  By=='XPATH':
                element = wait.until(EC.visibility_of_all_elements_located((AppiumBy.XPATH, '//XCUIElementTypeStaticText[@name="'+AttributeValue+'"]'))) 
                element = wait.until(EC.visibility_of_all_elements_located((AppiumBy.XPATH, '//XCUIElementTypeStaticText[@label="'+AttributeValue+'"]'))) 
                element = wait.until(EC.visibility_of_all_elements_located((AppiumBy.XPATH, '//XCUIElementTypeStaticText[contains(@value, "'+AttributeValue+'")]'))) 
                element = driver.find_element(AppiumBy.XPATH, '//XCUIElementTypeStaticText[contains(@value, "'+AttributeValue+'")]')
            elif By=='ID':
                element = wait.until(EC.visibility_of_all_elements_located((AppiumBy.ACCESSIBILITY_ID, AttributeValue))) 
                element = driver.find_element(AppiumBy.ACCESSIBILITY_ID, AttributeValue)
        elif driver.capabilities.get('platformName')=='mp' :
                print("其他平台")
        return element

    except NoSuchElementException as nsee:
        print(f"元素未找到错误: {nsee}")
        allure.attach(driver.get_screenshot_as_png(), name="元素未找到错误", attachment_type=allure.attachment_type.PNG)
        raise 
    except Exception as e:
        print(f"未知错误: {e}")
        allure.attach(driver.get_screenshot_as_png(), name="未知错误", attachment_type=allure.attachment_type.PNG)
        raise      
